//
//  DistributionScopeViewController.m
//  PigMarket
//
//  Created by mac on 2019/5/20.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "TribeRangeViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "TribeRangeCell.h"
#import "MapSearchResultView.h"

@interface TribeRangeViewController ()<MAMapViewDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
/**
 mapView
 */
@property (nonatomic , strong) MapViewManager *mapView;
/**
 searchBar
 */
@property (nonatomic , strong) UISearchBar *searchBar;
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 部落数组
 */
@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 经纬度数组
 */
@property (nonatomic , strong) NSMutableArray *rangArr;
/**
 搜索结果Arr
 */
@property (nonatomic , strong) NSMutableArray *searchResultArr;

@end
@implementation TribeRangeViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"配送范围";
    [self setUpNav];
    [self setUpView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //隐藏
    [[MapSearchResultView sharedInstance] hide];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

}
#pragma mark - init method
- (void)setUpNav {

    self.navigationItem.titleView = self.searchBar;
}
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(263);
    }];
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(263, 0, 0, 0));
    }];
}

- (void) initAction {

    //搜索周边数据回调
    @weakify(self);
    [self.mapView setSearchResultBlock:^(NSMutableArray *searchResultArr) {
        @strongify(self);
       
        [self.searchResultArr removeAllObjects];
        [self.searchResultArr addObjectsFromArray:searchResultArr];
        [self.myTableView reloadData];
    }];

}

- (void)initData {
    [self tribeRangeRequest];
}

#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //最多显示20条数据
    return self.searchResultArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TribeRangeCell *cell = [TribeRangeCell cellWithTableView:tableView];
    if (self.searchResultArr.count > indexPath.row) {
        MapSearchResult *searchResultModel = self.searchResultArr[indexPath.row];
        [cell configCellWithSearchResultModel:searchResultModel];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MapSearchResult *searchResultModel = self.searchResultArr[indexPath.row];
    if (searchResultModel.isInside) {
        NSString *latitude = [NSString stringWithFormat:@"%f",searchResultModel.latitude];
        NSString *longitude = [NSString stringWithFormat:@"%f",searchResultModel.longitude];
        NSDictionary *userInfoDic = @{@"lat":latitude,
                                      @"lon":longitude,
                                      @"localName":searchResultModel.detailAddress};
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidSelectCellLocationChange object:nil userInfo:userInfoDic];
        
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self toastWithContent:@"此区域未开通"];

    }
}

#pragma mark - searchDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES]; // 动画显示取消按钮
    
    //显示view
    [[MapSearchResultView sharedInstance] showSearchResultViewWithFrame:CGRectMake(0, TopBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-TopBarHeight)];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        [[MapSearchResultView sharedInstance] removeSearchData];
    }
}
//结束输入
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
}
//点击取消
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    [[MapSearchResultView sharedInstance] hide];
    [searchBar setShowsCancelButton:NO animated:YES]; // 动画显示取消按钮
}

//键盘上的搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self userSearchWithAddress:searchBar.text];
    [self.searchBar resignFirstResponder];
}
#pragma mark - target action

#pragma mark - private method
//配送范围数据请求
- (void)tribeRangeRequest {
    @weakify(self);
    [[[PigMarketApi sharedInstance] getTribeRange] subscribeNext:^(TribeRangeList * _Nullable tribeRangeList) {
        @strongify(self);
        [self.dataArr addObjectsFromArray:tribeRangeList.list];

        [self configMapRangeData];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}


//配送范围数据
- (void)configMapRangeData {
    for (TribeRange *model in self.dataArr) {
        [self.rangArr addObject:model.raglist];
    };
    @weakify(self);
    [self.mapView configMapWithDataArr:self.rangArr failureBlock:^(BOOL isFailure) {
        
        @strongify(self);
        [self toastWithContent:@"定位失败"];
    }];
}
//用户地址搜索
- (void)userSearchWithAddress:(NSString *)address {
    @weakify(self);
    [self.mapView userSearchAddressWithInputAddress:address completeBlock:^(NSMutableArray *addressArr) {
        @strongify(self);
        if (addressArr.count == 0) {
            [self toastWithContent:@"搜索不到输入地址"];
            [[MapSearchResultView sharedInstance] removeSearchData];
            return ;
        }
        //搜索结果页面赋值
        [self configMapSearchResultViewWithDataArr:addressArr];
    }];
}
//搜索结果页面赋值
- (void)configMapSearchResultViewWithDataArr:(NSMutableArray *)dataArr {
    @weakify(self);
    [[MapSearchResultView sharedInstance] configTableViewWithDataArr:dataArr completeBlock:^(UserSearchAddressResult *model) {
        @strongify(self);
        if (model.isInside) {
            NSString *latitude = [NSString stringWithFormat:@"%f",model.latitude];
            NSString *longitude = [NSString stringWithFormat:@"%f",model.longitude];
            
            NSDictionary *userInfoDic = @{@"lat":latitude,
                                          @"lon":longitude,
                                          @"localName":model.detailAddress,
                                          @"localCode":model.discrictCode};
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidSelectCellLocationChange object:nil userInfo:userInfoDic];
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self toastWithContent:@"此区域未开通"];
        }
    }];
}


#pragma mark - getter and setter
- (MapViewManager *)mapView {
    if (!_mapView) {
        _mapView = [[MapViewManager alloc] init];
    }
    return _mapView;
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
- (NSMutableArray *)rangArr {
    if (!_rangArr) {
        _rangArr = [[NSMutableArray alloc] init];
    }
    return _rangArr;
}
- (NSMutableArray *)searchResultArr {
    if (!_searchResultArr) {
        _searchResultArr = [[NSMutableArray alloc] init];
    }
    return _searchResultArr;
}
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.rowHeight = 68;
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _myTableView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        
        //光标颜色
        //    self.searchBar.tintColor = [UIColor colorWithHexString:@"#F7F7F7"];
        
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchBar.placeholder = @"请输入要搜索的内容";
        _searchBar.delegate = self;
        
        UITextField*searchField = [_searchBar valueForKey:@"_searchField"];
        //更改searchBar 中PlaceHolder 字体颜色
        [searchField setValue:[UIColor colorWithHexString:@"#B2B2B2"] forKeyPath:@"_placeholderLabel.textColor"];
        [searchField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
     
    }
    return _searchBar;
}

@end
